package com.wys.mall.service.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Package com.wys.mall.service.utils
 * @Author charlin
 * @Version: v1.0
 * @Date 2021-06-1721:20
 * @Copyright: 2021 www.wyscha.com Inc. All rights reserved.
 */
public class OssUtil {

    public static Map<String, String> doGet(OSS ossClient, String endpoint, String bucket, String accessId) throws ServletException, IOException {
        String host = "https://" + bucket + "." + endpoint;
//        String callbackUrl = "http://88.88.88.88:8888";
        String dir = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/";
        // 创建OSSClient实例。
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            return respMap;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }


//    protected boolean VerifyOSSCallbackRequest(HttpServletRequest request, String ossCallbackBody)
//            throws NumberFormatException, IOException {
//        boolean ret = false;
//        String autorizationInput = new String(request.getHeader("Authorization"));
//        String pubKeyInput = request.getHeader("x-oss-pub-key-url");
//        byte[] authorization = BinaryUtil.fromBase64String(autorizationInput);
//        byte[] pubKey = BinaryUtil.fromBase64String(pubKeyInput);
//        String pubKeyAddr = new String(pubKey);
//        if (!pubKeyAddr.startsWith("https://gosspublic.alicdn.com/")
//                && !pubKeyAddr.startsWith("https://gosspublic.alicdn.com/")) {
//            System.out.println("pub key addr must be oss addrss");
//            return false;
//        }
//        String retString = executeGet(pubKeyAddr);
//        retString = retString.replace("-----BEGIN PUBLIC KEY-----", "");
//        retString = retString.replace("-----END PUBLIC KEY-----", "");
//        String queryString = request.getQueryString();
//        String uri = request.getRequestURI();
//        String decodeUri = java.net.URLDecoder.decode(uri, "UTF-8");
//        String authStr = decodeUri;
//        if (queryString != null && !queryString.equals("")) {
//            authStr += "?" + queryString;
//        }
//        authStr += "\n" + ossCallbackBody;
//        ret = doCheck(authStr, authorization, retString);
//        return ret;
//    }
//
//    protected void doPost(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//        String ossCallbackBody = GetPostBody(request.getInputStream(),
//                Integer.parseInt(request.getHeader("content-length")));
//        boolean ret = VerifyOSSCallbackRequest(request, ossCallbackBody);
//        System.out.println("verify result : " + ret);
//        // System.out.println("OSS Callback Body:" + ossCallbackBody);
//        if (ret) {
//            response(request, response, "{\"Status\":\"OK\"}", HttpServletResponse.SC_OK);
//        } else {
//            response(request, response, "{\"Status\":\"verify not ok\"}", HttpServletResponse.SC_BAD_REQUEST);
//        }
//    }
}
